/* Password routines.
 *
 * Copyright 2008 Cian Synnott.
 * 
 * $Id: password.c 19 2009-11-27 20:46:48Z cian $
 */
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <termios.h>

/* Toggles echo on your terminal. */
void toggle_echo(void) {
  struct termios terminal;

  tcgetattr(0, &terminal);

  if (terminal.c_lflag & ECHO) {
    terminal.c_lflag &= (~ECHO);
  } else {
    terminal.c_lflag |= ECHO;
  }
  
  tcsetattr(0, TCSANOW, &terminal);
}

/* See password.h */
#define PROMPT_BUFFER_LEN 128
char *get_password(char *prompt, ...) {
  char formatted_prompt[PROMPT_BUFFER_LEN];
  char *password = NULL;
  va_list args;
  size_t size = 0;

  va_start(args, prompt);
  vsnprintf(formatted_prompt, PROMPT_BUFFER_LEN, prompt, args);
  va_end(args);

  printf("%s", formatted_prompt);
  toggle_echo();
  if (getline(&password, &size, stdin) < 0) 
    return NULL;
  toggle_echo();

  if (password[strlen(password) - 1] == '\n')
    password[strlen(password) - 1] = 0;
  puts("\n");

  return password;
}
